package com.example.moshudriver.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.BeeFramework.Utils.ImageUtil;
import com.BeeFramework.activity.BaseActivity;
import com.BeeFramework.model.BusinessResponse;
import com.BeeFramework.view.RoundedWebImageView;
import com.BeeFramework.view.ToastView;
import com.sgr.dykdriver.R;
import com.example.moshudriver.model.UserModel;
import com.example.moshudriver.protocol.ApiInterface;
import com.example.moshudriver.protocol.ENUM_USER_GENDER;
import com.example.moshudriver.protocol.USER;
import com.example.moshudriver.protocol.usercertifyResponse;
import com.example.moshudriver.tools.MessageConstant;
import com.example.moshudriver.tools.O2OMobileAppConst;
import com.example.moshudriver.utils.MyApplication;
import com.example.moshudriver.utils.VerifyIdCard;
import com.external.androidquery.callback.AjaxStatus;
import com.external.eventbus.EventBus;

public class B3_DriverApplyActivity extends BaseActivity implements
		BusinessResponse, View.OnClickListener {
	public static final String USER_ID = "user_id";
	private int mUserId;
	private UserModel mUserModel;
	private TextView tv_driver_head_portrait, tv_driver_identification;
	private TextView tv_driver_gender;

	private EditText et_driver_real_name;
	private USER mUser;
	private EditText et_driver_identification, et_motoId;
	private Button btn_apply;
	private ImageView iv_backhome;
	private RoundedWebImageView driver_avatar, v_avatar;
	private Dialog mDialog;
	private File mFileDir;

	private final int REQUEST_CAMERA = 1;
	private final int REQUEST_PHOTO = 2;
	private final int REQUEST_PHOTOZOOM = 3;
	private File mFile;
	private String mFileName = "";
	private String mImagePath;
	private File mFileZoomDir;
	private UserModel mUserApply;
	private Bitmap photo;
	private File avatar;// 相片文件
	private ENUM_USER_GENDER sex;
	private static String mobile, password, invite;
	private File vetify_avatar;// 第二张相片文件
	public boolean isfirstpicture = false;// true表示点击第一张相片
	public boolean issencondpicture = false;// true表示点击选择第二张照片
	private TextView tv_agree;
	private CheckBox cb_agree;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_driver_apply);
		initView();

		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		mobile = bundle.getString(B1_SignupVerifyActivity.MOBILE);
		password = bundle.getString(B1_SignupVerifyActivity.PASSWORD);
		invite = bundle.getString(B1_SignupVerifyActivity.INVITE);
		mUserModel = new UserModel(this);
		mUserModel.addResponseListener(this);
		MyApplication.getInstance().addActivity(this);
		EventBus.getDefault().register(this);
	}

	private void initView() {
		mUserApply = new UserModel(this);
		mUserApply.addResponseListener(this);
		mUserId = getIntent().getIntExtra(USER_ID, 0);
		tv_driver_head_portrait = (TextView) findViewById(R.id.tv_driver_head_portrait);
		et_driver_real_name = (EditText) findViewById(R.id.et_driver_real_name);
		tv_driver_gender = (TextView) findViewById(R.id.tv_driver_gender);
		tv_driver_gender.setText("男");
		cb_agree = (CheckBox) findViewById(R.id.cb_agree);

		et_motoId = (EditText) findViewById(R.id.et_motoId);
		et_driver_identification = (EditText) findViewById(R.id.et_driver_identification);
		tv_driver_identification = (TextView) findViewById(R.id.tv_driver_identification);
		btn_apply = (Button) findViewById(R.id.btn_apply);
		iv_backhome = (ImageView) findViewById(R.id.iv_backhome);
		driver_avatar = (RoundedWebImageView) findViewById(R.id.driver_avatar);
		v_avatar = (RoundedWebImageView) findViewById(R.id.v_avatar);

		tv_agree = (TextView) findViewById(R.id.tv_agree);
		tv_agree.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
		tv_agree.setOnClickListener(this);
		tv_driver_identification.setOnClickListener(this);
		et_driver_identification.setOnClickListener(this);
		driver_avatar.setOnClickListener(this);
		btn_apply.setOnClickListener(this);
		iv_backhome.setOnClickListener(this);
		tv_driver_head_portrait.setOnClickListener(this);
		tv_driver_gender.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.tv_driver_identification:// 第二张相片
			issencondpicture = true;
			isfirstpicture = false;

			showDialog();

			// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			// startActivityForResult(intent, 1);
			break;
		case R.id.tv_driver_gender:
			showSelectGenderDialog();
			break;
		case R.id.tv_driver_head_portrait:// 第一个相片
			issencondpicture = false;
			isfirstpicture = true;
			showDialog();
			break;

		case R.id.tv_agree:
			Intent i = new Intent(B3_DriverApplyActivity.this,
					B3_DeclareActivity.class);
			startActivity(i);
			break;
		case R.id.iv_backhome:
			CloseKeyBoard();
			finish();
			break;
		case R.id.btn_apply:
			String driver_real_name = et_driver_real_name.getText().toString()
					.trim();
			String driver_identification = et_driver_identification.getText()
					.toString().trim();
			if (tv_driver_gender.getText().toString().equals("女")) {
				sex = ENUM_USER_GENDER.WOMAN;
			} else {
				sex = ENUM_USER_GENDER.MAN;
			}

			if ("".equals(driver_real_name)) {// 真实姓名
				ToastView toast = new ToastView(this,
						getString(R.string.please_input_your_real_name));
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				et_driver_real_name.requestFocus();
				
			} else if (sex == null) {
				ToastView toast = new ToastView(this,
						getString(R.string.please_input_verify_sex));
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				tv_driver_gender.requestFocus();
			} else if ("".equals(driver_identification)) {// 身份证
				ToastView toast = new ToastView(this,
						getString(R.string.please_input_verify_indentification));
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				et_driver_identification.setText("");
				et_driver_identification.requestFocus();
			} else if (driver_identification.length() < 17||!VerifyIdCard.verify(driver_identification)) {
				ToastView toast = new ToastView(this,
						getString(R.string.please_input_verify_indentification));
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				et_driver_identification.requestFocus();
			} else if (avatar == null) {
				ToastView toast = new ToastView(this,
						getString(R.string.please_input_verify_head));
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				et_driver_identification.requestFocus();
			} else if (vetify_avatar == null) {
				ToastView toast = new ToastView(this,
						getString(R.string.please_input_verify_head));
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				et_driver_identification.requestFocus();
			} else if (mobile == null) {
				ToastView toast = new ToastView(this,
						getString(R.string.please_input_mobile_phone));
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				et_driver_identification.requestFocus();
			} else if (!cb_agree.isChecked()) {
				ToastView toast = new ToastView(this,
						"请同意递一快注册协议！");
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			}else{

				mUserApply.certify(driver_real_name, driver_identification,
						sex, avatar, mobile, password, invite, vetify_avatar,
						et_motoId.getText() == null ? "" : et_motoId.getText()
								.toString());

			}
			break;
		}

	}

	private void showSelectGenderDialog() {
		View view = View.inflate(this, R.layout.gender_view, null);
		mDialog = new Dialog(this, R.style.dialog);
		mDialog.setContentView(view);

		mDialog.setCanceledOnTouchOutside(true);
		mDialog.show();

		TextView gender_men = (TextView) view.findViewById(R.id.gender_men);
		TextView gender_women = (TextView) view.findViewById(R.id.gender_women);

		gender_men.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mDialog.dismiss();
				tv_driver_gender.setText("男");
			}
		});

		gender_women.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mDialog.dismiss();
				tv_driver_gender.setText("女");
			}
		});
	}

	private void showDialog() {
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.photo_dialog, null);
		mDialog = new Dialog(this, R.style.dialog);
		mDialog.setContentView(view);

		mDialog.setCanceledOnTouchOutside(true);
		mDialog.show();
		LinearLayout requsetCameraLayout = (LinearLayout) view
				.findViewById(R.id.register_camera);
		LinearLayout requestPhotoLayout = (LinearLayout) view
				.findViewById(R.id.register_photo);
		// 调用系统拍照
		requsetCameraLayout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generate
				mDialog.dismiss();
				if (mFileDir == null) {
					mFileDir = new File(O2OMobileAppConst.FILEPATH + "img/");
					if (!mFileDir.exists()) {
						mFileDir.mkdirs();
					}
				}

				mFileName = O2OMobileAppConst.FILEPATH + "img/" + "temp.jpg";
				mFile = new File(mFileName);
				Uri imageuri = Uri.fromFile(mFile);
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri);
				intent.putExtra("return-data", false);
				startActivityForResult(intent, REQUEST_CAMERA);
			}
		});

		requestPhotoLayout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mDialog.dismiss();
				Intent picture = new Intent(Intent.ACTION_PICK,
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				startActivityForResult(picture, REQUEST_PHOTO);
			}
		});
	}
	

	@SuppressWarnings("static-access")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {

			if (requestCode == REQUEST_CAMERA) {// 拍照返回的数据
				File files = new File(mFileName);
				if (files.exists()) {
					mImagePath = mFileName;

					
					if (isfirstpicture) {

						mImagePath = startPhotoZoom(
								Uri.fromFile(new File(mImagePath))
								);
					}else{
						mImagePath = startPhotoZoom1(
								Uri.fromFile(new File(mImagePath))
								);
					}
					
					

				}
			} else if (requestCode == REQUEST_PHOTO) {// 选择本地照片返回数据
				if (data != null) {
					Uri selectedImage = data.getData();

					
					if (isfirstpicture) {

						mImagePath = startPhotoZoom(selectedImage);
					}else{
						mImagePath = startPhotoZoom1(selectedImage);
					}
					

				}

			} else if (requestCode == REQUEST_PHOTOZOOM) {// 头像裁剪
		      if(mImagePath==null){
		    	  Toast.makeText(B3_DriverApplyActivity.this, "图片处理失败", 2000).show();
		    	  return;
		      }
				File f = new File(mImagePath);
				if (f.exists()) {

					if (isfirstpicture) {
						System.out.println("显示图片");
						System.out.println("avatarmImagePath" + mImagePath);
						avatar = new File(ImageUtil.zoomImage(mImagePath, 350));
						System.out.println("avatar" + avatar);

						
						try {
							InputStream is = new FileInputStream(mImagePath);
							Bitmap	bmpDefaultPic = BitmapFactory.decodeStream(is); 
							driver_avatar.setImageBitmap(bmpDefaultPic);
//							BufferedImage image = ImageIO.read(is);
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
//						Bitmap bmpDefaultPic = BitmapFactory.decodeFile(
//								mImagePath, null);
//						driver_avatar.setImageBitmap(bmpDefaultPic);
					}
					if (issencondpicture) {
						vetify_avatar = new File(ImageUtil.zoomImage1(
								mImagePath, 800));
						System.out.println("vetify_avatar" + vetify_avatar);
						System.out.println("vetify_avatarmImagePath"
								+ mImagePath);
						
						try {
							InputStream is = new FileInputStream(mImagePath);
							Bitmap	bmpDefaultPic = BitmapFactory.decodeStream(is); 
							v_avatar.setImageBitmap(bmpDefaultPic);
//							BufferedImage image = ImageIO.read(is);
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
//						
					
					}
					System.out.println("保存完成");
					// Bundle extras = data.getExtras();
					// if (extras != null) {
					// photo = extras.getParcelable("data");
					// if(photo!=null){
					// Drawable drawable = new BitmapDrawable(photo);
					//
					// if(isfirstpicture){
					// driver_avatar.setImageDrawable(drawable);
					// }
					// if(issencondpicture){
					// v_avatar.setImageDrawable(drawable);
					// }
					//
					//
					// }
					//
					// }
					// 获得了头像文件

				} else {
					ToastView toast = new ToastView(this,
							getString(R.string.photo_not_exsit));
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				}
			}
		}
	}
	
	
	private String startPhotoZoom1(Uri uri) {
		
		System.out.println("开始截图");
		mFileZoomDir = null;
		if (mFileZoomDir == null) {
			mFileZoomDir = new File(O2OMobileAppConst.FILEPATH1 + "img/");
			if (!mFileZoomDir.exists()) {
				mFileZoomDir.mkdirs();
			}
		}

		String fileName = "/temp.jpg";

		String filePath = mFileZoomDir + fileName;
		File loadingFile = new File(filePath);

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 400);
		intent.putExtra("aspectY", 400);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(loadingFile));// 输出到文件
																			// 当加了这句之后
																			// 和
																			// 下面设置为true时无法跳转
		intent.putExtra("outputFormat", "PNG");// 返回格式

		intent.putExtra("return-data", false); // 要通过Intent传递截获的图片
		startActivityForResult(intent, REQUEST_PHOTOZOOM);
		System.out.println("结束截图");
		return filePath;

	}

	private String startPhotoZoom(Uri uri) {
		
		System.out.println("开始截图");
		mFileZoomDir = null;
		if (mFileZoomDir == null) {
			mFileZoomDir = new File(O2OMobileAppConst.FILEPATH + "img/");
			if (!mFileZoomDir.exists()) {
				mFileZoomDir.mkdirs();
			}
		}

		String fileName = "/temp.jpg";

		String filePath = mFileZoomDir + fileName;
		File loadingFile = new File(filePath);

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 400);
		intent.putExtra("aspectY", 400);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(loadingFile));// 输出到文件
																			// 当加了这句之后
																			// 和
																			// 下面设置为true时无法跳转
		intent.putExtra("outputFormat", "PNG");// 返回格式

		intent.putExtra("return-data", false); // 要通过Intent传递截获的图片
		startActivityForResult(intent, REQUEST_PHOTOZOOM);
		System.out.println("结束截图");
		return filePath;

	}

	@Override
	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException {
		if (url.endsWith(ApiInterface.USER_CERTIFY)) {
			usercertifyResponse response = new usercertifyResponse();
			response.fromJson(jo);
			if (response.succeed == 1) {
				Toast.makeText(B3_DriverApplyActivity.this,
						"申请成功，等待审核通过即可登录", Toast.LENGTH_LONG).show();
				Intent intent=new Intent(B3_DriverApplyActivity.this, B0_SigninActivity.class);
				startActivity(intent);
				finish();
			} else {
				et_driver_real_name.requestFocus();
			}
		}
	}

	// 关闭键盘
	private void CloseKeyBoard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(et_driver_real_name.getWindowToken(), 0);
	}

	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	public void onEvent(Object event) {
		Message message = (Message) event;
		if (message.what == MessageConstant.SIGN_UP_SUCCESS) {
			finish();
		}
	}
}
